package com.xcdh.ittools.parsing;

import org.apache.ibatis.ognl.Ognl;
import org.apache.ibatis.ognl.OgnlException;
import org.apache.ibatis.parsing.TokenHandler;
import org.apache.ibatis.scripting.ScriptingException;

import java.util.regex.Pattern;

public class ITToolDynamicTokenParser implements TokenHandler {
    private Object parameter ;

    private Pattern injectionFilter;

    public ITToolDynamicTokenParser(Object parameter , Pattern injectionFilter ){
        this.parameter = parameter ;
        this.injectionFilter = injectionFilter;
    }
    public ITToolDynamicTokenParser(Object parameter){
        this(parameter , null );
    }
    @Override
    public String handleToken(String content) {
        try {
            Object value = Ognl.getValue(content, this.parameter);
            String srtValue = value == null ? "" : String.valueOf(value);
            checkInjection(srtValue);
            return srtValue;
        } catch (OgnlException e) {
            throw new RuntimeException(e);
        }
    }
    private void checkInjection(String value) {
        if (injectionFilter != null && !injectionFilter.matcher(value).matches()) {
            throw new ScriptingException("Invalid input. Please conform to regex" + injectionFilter.pattern());
        }
    }
}
